package com.ly.mp.cmc.common.filter;

import lombok.Getter;
import lombok.Setter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * @Author: ly-songpengfei
 * @Date: 2025/8/5 11:29
 * @Description: 请求参数封装
 * @Version: 1.0
 */
@Setter
@Getter
public class RequestParameterWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params;

    public RequestParameterWrapper(HttpServletRequest request) {
        super(request);
        this.params = new HashMap();
        this.params.putAll(request.getParameterMap());
    }

    public RequestParameterWrapper(HttpServletRequest request, Map<String, Object> extendParams) {
        this(request);
        this.addAllParameters(extendParams);
    }

    private void addAllParameters(Map<String, Object> extendParams) {
        Iterator iter = extendParams.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry) iter.next();
            this.addParameter(entry.getKey(), entry.getValue());
        }
    }

    private void addParameter(String key, Object value) {
        if (value != null) {
            if (value instanceof String[]) {
                this.params.put(key, (String[]) value);
            } else if (value instanceof String) {
                this.params.put(key, new String[]{(String) value});
            } else {
                this.params.put(key, new String[]{String.valueOf(value)});
            }
        }
    }

    @Override
    public String getParameter(String name) {
        String[] values = this.params.get(name);
        return values != null && values.length != 0 ? values[0] : null;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        Enumeration parameterNames = new Vector(this.params.keySet()).elements();
        return parameterNames;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = this.params.get(name);
        return values != null && values.length != 0 ? values : null;
    }
}
